/**
 * 
 */
package jm.lib.web.jsf.converter;

import java.sql.Time;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import jm.lib.util.StrUtil;

/**
 * @author JimingLiu
 *
 */
public class SqlTimeConverter implements Converter {

	private boolean useNowAsDefault;

	/**
	 * SqlDateConverter(false);
	 *
	 */
	public SqlTimeConverter() {
		this(false);
	}

	/**
	 * If there have not value, use <code>now</code> as default value
	 * 
	 * @param useNowAsDefault
	 */
	public SqlTimeConverter(boolean useNowAsDefault) {
		this.useNowAsDefault = useNowAsDefault;
	}

	/* (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
	 */
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
			throws ConverterException {
		Time result;
		if (StrUtil.isEmpty(arg2)) {
			if(useNowAsDefault) {
				result = new Time(System.currentTimeMillis());
			} else {
				throw new ConverterException(
						"Time format should be 'hh:mm:ss', instead of empty");
			}
		} else {
			String input = arg2.replace('/', '-');
			try {
				result = Time.valueOf(input);
			} catch (IllegalArgumentException e) {
				throw new ConverterException(
						"Time format should be 'hh:mm:ss'.(" + input + ")");
			}
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
			throws ConverterException {
		String result;
		if(null == arg2) {
			if(useNowAsDefault) {
				result = new Time(System.currentTimeMillis()).toString();
			} else {
				result = "";
			}
		} else {
			result = arg2.toString();
		}
		return result;
	}

}
